package com.qujia.web.controller.system;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.Constants;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysRole;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginBody;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.domain.vo.SysUserVo;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.ServletUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.framework.manager.AsyncManager;
import com.qujia.framework.manager.factory.AsyncFactory;
import com.qujia.framework.web.service.TokenService;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.Station;
import com.qujia.station.domain.form.StaffForm;
import com.qujia.station.domain.vo.EnterpriseAndStationVo;
import com.qujia.station.domain.vo.StaffVO;
import com.qujia.station.service.*;
import com.qujia.system.domain.SysAgent;
import com.qujia.system.domain.SysUserRole;
import com.qujia.system.mapper.SysUserMapper;
import com.qujia.system.mapper.SysUserRoleMapper;
import com.qujia.system.service.ISysAgentService;
import com.qujia.system.service.ISysPostService;
import com.qujia.system.service.ISysRoleService;
import com.qujia.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author qujia
 */
@Api(tags = "登录用户管理", description = "登录用户管理")
@RestController
@RequestMapping("/system/user")
@Slf4j
public class SysUserController extends BaseController {

    @Autowired
    private IStationService stationService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IStaffService staffService;
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysAgentService sysAgentService;
    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private MemberManagementService memberManagementService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {

        SysUser loginSysUser = SecurityUtils.getLoginSysUser();
        LoginUser current = SecurityUtils.getLoginUser();
        List<SysUser> list = new ArrayList<>();
        if(user.getAuthorId()!=null){
            if (user.getAuthorId()  == 1L) {

            } else {
                SysUser aSysUser = userMapper.selectUserById(Long.valueOf(user.getAuthorId()));
                startPage();
                if (StringUtils.equals("7", aSysUser.getUserLevel())) {
                    user.setEnterpriseIdListForAuthor(null);
                    user.setSupremeLevelId(aSysUser.getUserId());
                    list= userMapper.selectUserListBySupremeLevel(user);
                    return getDataTable(list);
                }else{
                    return getDataTable(list);
                }
            }
        }

        if (StringUtils.isNull(loginSysUser.getUserLevel())) {
            startPage();
            list = userService.selectUserList(user);
        } else if (StringUtils.equals("7", loginSysUser.getUserLevel())) {
                user.setEnterpriseIdListForAuthor(null);
                user.setNotUserLevel("7");
                user.setSupremeLevelId(loginSysUser.getUserId());
            startPage();
            list = userMapper.selectUserListBySupremeLevel(user);
        }else if (StringUtils.equals("6", loginSysUser.getUserLevel())) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                user.setEnterpriseIdListForAuthor(enterpriseIds);
                user.setNotUserLevel("6");
                startPage();
                list = userService.selectUserList(user);
            }
        }else if (StringUtils.equals("5", loginSysUser.getUserLevel())) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(current.getUser());
            List<Long> enterpriseIds = itemIds.getEnterpriseIds();
            if (enterpriseIds != null && enterpriseIds.size()>0) {
                user.setEnterpriseIdListForAuthor(enterpriseIds);
                user.setNotUserLevel("5");
                startPage();
                list = userService.selectUserList(user);
            }
        }else if (StringUtils.equals("1", loginSysUser.getUserLevel())) {
            user.setEnterpriseId(loginSysUser.getEnterpriseId());
            user.setNotUserLevel("1");
            startPage();
            list = userService.selectUserList(user);
        }else if (StringUtils.equals("2", loginSysUser.getUserLevel())) {
            List<Integer> aRoles =   roleService.selectRoleListByUserId(loginSysUser.getUserId());
            for(Integer roleItem : aRoles){
                SysRole bSysRole =    roleService.selectRoleById(new Long(roleItem));
                if( bSysRole.getRoleName().equals("员工")){
                    return getDataTable(list);
                }
            }
            user.setStationId(loginSysUser.getStationId());
            user.setNotUserLevel("2");
            StaffForm form = new StaffForm();
            form.setEnterpriseId(loginSysUser.getEnterpriseId());
            form.setStationId(loginSysUser.getStationId());
            StaffVO staffVO = StaffVO.of(form);
            staffVO.setUserLevel(UserConstants.LEVEL_THREE);
            startPage();
            List<StaffVO> staffVOS = staffService.queryStaffList(staffVO);
        for(StaffVO staffItem :staffVOS){
            SysUser sysUserItem = userService.getById(staffItem.getUserId());
            list.add(sysUserItem);
        }
        }

        return getDataTable(list);
    }

    @GetMapping("/listEnterpriseUser")
    @ApiOperation(value = "获取员工列表", notes = "获取员工列表")
    public List<SysUser> listEnterpriseUser(SysUser user) {

        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user2 = current.getUser();

        List<SysUser> list = new ArrayList<>();

        if (null != user2.getUserLevel() && user2.getUserLevel().equals("5")) {
            ArrayList<SysUser> sysUsersList = new ArrayList<>();
            log.info("输入的负责人id：{}", user2.getUserId());
            List<Long> managerEnterpriseId = teamManagementService.getManagerEnterpriseId(user2.getUserId());
            log.info("该负责人id:{} , 所管理的油企id：{}", user2.getUserId(), managerEnterpriseId);
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                for (Long id : managerEnterpriseId) {
                    SysUser sysUser = new SysUser();
                    sysUser.setEnterpriseId(id);
                    sysUser.setUserLevel("2");
                    List<SysUser> sysUsers = userService.selectUserList(sysUser);
                    sysUsersList.addAll(sysUsers);
                }
            }

            return sysUsersList;
        }
        if (null != user2.getUserLevel() && user2.getUserLevel().equals("6")) {

            ArrayList<SysUser> sysUsersList = new ArrayList<>();
            log.info("输入的业务员id：{}", user2.getUserId());
            List<Long> managerEnterpriseId = memberManagementService.getMemberEnterpriseId(user2.getUserId());
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                log.info("该业务员id:{} , 所管理的油企id：{}", user2.getUserId(), managerEnterpriseId);
                for (Long id : managerEnterpriseId) {
                    SysUser sysUser = new SysUser();
                    sysUser.setEnterpriseId(id);
                    sysUser.setUserLevel("2");
                    List<SysUser> sysUsers = userService.selectUserList(sysUser);
                    sysUsersList.addAll(sysUsers);
                }
            }
            return sysUsersList;
        }
        if (null != user2.getUserLevel() && user2.getUserLevel().equals("2")) {
            user.setUserLevel("2");
            user.setStationId(current.getUser().getStationId());
            user.setEnterpriseId(current.getUser().getEnterpriseId());
            return userService.selectUserList(user);

        }

        if (current.getUser().getEnterpriseId() == null) {
            list = userService.selectUserList(user);
        } else {
            user.setUserLevel("2");
            user.setEnterpriseId(current.getUser().getEnterpriseId());
            list = userService.selectUserList(user);
        }
        return list;

    }

    @GetMapping("/listUser")
    public TableDataInfo listUser(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        for (int i = 0; i < list.size(); i++) {
            List<String> gun = new ArrayList<>();
            List<Long> gunnumber = new ArrayList<>();
            List<String> gunList1 = new ArrayList<>();
            if (list.get(i).getGun() != null) {
                String[] gunls = list.get(i).getGun().split(",");
                for (String ss : gunls) {
                    gun.add(ss);
                    gunnumber.add(Long.parseLong(ss));
                }
                Long[] value = new Long[gunnumber.size()];
                for (int ss = 0; ss < gunnumber.size(); ss++) {
                    value[ss] = gunnumber.get(ss);
                }
                Long temp = Long.parseLong("0");
                for (int tt = 0; tt < value.length; tt++) {
                    for (int m = tt + 1; m < value.length; m++) {
                        if (value[tt] > value[m]) {
                            temp = value[m];
                            value[m] = value[tt];
                            value[tt] = temp;
                        }
                    }
                }

                for (Long mm : value) {
                    gunList1.add(mm + "");
                }
            }
            if (list.get(i).getPushUserIds() != null) {
                list.get(i).setIdList(Arrays.asList(list.get(i).getPushUserIds().split(",")));
            } else {
                list.get(i).setIdList(new ArrayList<>());
            }
            list.get(i).setGunList(gunList1);

        }
        return getDataTable(list);
    }

    @GetMapping("/listCooperator")
    @ApiOperation(value = "获取合伙人列表", notes = "获取合伙人列表")
    public TableDataInfo listCooperator(SysUser user) {
        startPage();
        user.setUserLevel("7");
        List<SysUser> list = userService.selectUserList(user);
        if (list == null || list.size() < 1) {
            return null;
        }
        List<String> collect = list.stream().map(SysUser::getUserName).collect(Collectors.toList());
        //下属油企数量
        SysUser sysUser = new SysUser();
        sysUser.setCreateByList(collect);
        sysUser.setUserLevel("1");
        List<SysUser> sysUsers = userService.selectUserList(sysUser);
        Map<String, List<SysUser>> collect1 = sysUsers.stream().collect(Collectors.groupingBy(SysUser::getCreateBy));
        for (SysUser sysUser1 : list) {
            if (StringUtils.isNotNull(collect1.get(sysUser1.getCreateBy()))) {
                sysUser1.setSubNum(collect1.get(sysUser1.getCreateBy()).size());
            } else {
                sysUser1.setSubNum(0);
            }
        }

        return getDataTable(list);
    }

    @GetMapping("/cooperator")
    @ApiOperation(value = "获取合伙人列表", notes = "获取合伙人列表")
    public AjaxResult Cooperator(){
        SysUser user = new SysUser();
        user.setUserLevel("7");
        List<SysUser> list = userService.selectUserList(user);
        SysUser aSysUser= new SysUser();
        aSysUser.setUserId(1L);
        aSysUser.setUserName("admin");
        list.add(aSysUser);
        return AjaxResult.success(list);
    }

    /**
     * 根据登录人获取等级
     */
    @GetMapping("/getLevel")
    @ApiOperation(value = "根据登录人获取等级", notes = "根据登录人获取等级")
    public AjaxResult getLevel() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUser byId = userService.getById(user.getUserId());
        HashMap<Integer, List<String>> map = new HashMap<>();
        map.put(1, Arrays.asList("7", "6", "5"));
        map.put(2, Collections.singletonList("1"));
        map.put(3, Arrays.asList("2", "3"));
        //如果是admin或者合伙人角色开放所有等级
        if (!StringUtils.isNull(user.getUserLevel()) ) {
            if (StringUtils.isNotNull(byId.getAuthLevel())) {
                //如果是区域经理、业务员
                if (SecurityUtils.isPartner()) {
                    if (StringUtils.equals("5", user.getUserLevel())) {
                        map.put(1, Collections.singletonList("6"));
                    } else if (StringUtils.equals("6", user.getUserLevel())){
                        map.remove(1);
                    } else if(StringUtils.equals("7", user.getUserLevel())) {
                        map.put(1, Arrays.asList("6", "5"));
                    }
                    //油企
                } else if (StringUtils.equals("1", user.getUserLevel())) {
                    map.remove(1);
                    map.remove(2);
                    //油站
                } else if (StringUtils.equals("2", user.getUserLevel())) {
                    map = new HashMap<>();
                    map.put(3, Collections.singletonList("3"));
                }
            } else {
                return AjaxResult.error("用户信息缺失，请联系管理员");
            }
        }
        return AjaxResult.success(map);
    }

    /**
     * 获取归属一级账号  标记 逻辑通
     */
    @GetMapping("/getFirstAccount")
    @ApiOperation(value = "获取归属一级账号", notes = "获取归属一级账号")
    public AjaxResult getFirstAccount() {
        SysUser loginSysUser = SecurityUtils.getLoginSysUser();
        SysUser sysUser = new SysUser();
        sysUser.setStatus("0");
        List<SysUser> sysUsers = new ArrayList<>();
        if (StringUtils.isNull(loginSysUser.getUserLevel())) {
            sysUser.setUserLevel("7");
            sysUsers = userService.selectUserList(sysUser);
            sysUsers.add(loginSysUser);
        } else if (StringUtils.equals("7", loginSysUser.getUserLevel())) {
            sysUsers.add(loginSysUser);
        }else{
            SysUser aSysUser =   userService.getById(loginSysUser.getSupremeLevelId())  ;
            sysUsers.add(aSysUser);
        }
        return AjaxResult.success(sysUsers);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("SysUserGetInfo")
    public AjaxResult getInfo()
    {
        Long userId = SecurityUtils.getLoginSysUser().getUserId();
        SysUser byId = userService.getById(userId);
        if (SecurityUtils.isAdmin(userId)){
            return AjaxResult.success(byId);
        }else if(byId.getUserLevel().equals("1")){
            Enterprise aEnterprise=    enterpriseService.selectEnterpriseById( byId.getEnterpriseId()) ;
            byId.setEnterpriseName(aEnterprise.getEnterpriseName());
            return AjaxResult.success(byId);
        }else if(byId.getUserLevel().equals("2")){
            Enterprise aEnterprise=    enterpriseService.selectEnterpriseById( byId.getEnterpriseId()) ;
            byId.setEnterpriseName(aEnterprise.getEnterpriseName());
            Station aStation =  stationService.selectStationById(byId.getStationId());
            byId.setStationName(aStation.getStationName());
            return AjaxResult.success(byId);
        }else{
            return AjaxResult.success(byId);
        }
    }

    /**
     * 获取可分配角色
     *
     * @return
     */
    @GetMapping("/getRoleByUser")
    public AjaxResult getRoles(String authLevel ) {
        QueryWrapper<SysRole> queryWrapper = null;
        Long userId = SecurityUtils.getLoginSysUser().getUserId();
        SysUser byId = userService.getById(userId);
        List<String> strings = new ArrayList<>();
        if(StringUtils.isNotEmpty(byId.getRoleId())){
            strings.addAll(Arrays.asList(byId.getRoleId().split(",")));
        }
              queryWrapper = new QueryWrapper<>();
            List<String> roleName = new ArrayList<>();
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginSysUser().getUserId())) {

            if (StringUtils.equals("7", authLevel)) {
                roleName.add("区域经理");
                roleName.add("业务员");
                roleName.add("员工");
                roleName.add("油企");
                roleName.add("油站");
            }
            if (StringUtils.equals("5", authLevel)) {
                roleName.add("业务员");
            }
            if (StringUtils.equals("6", authLevel)) {
            }
            if (StringUtils.equals("2", authLevel) || StringUtils.equals("3", authLevel)) {
                roleName.add("员工");
            }
            if (StringUtils.equals("1", authLevel)) {
                roleName.add("员工");
                roleName.add("油站");
            }

            if (roleName == null || roleName.size()<1){
                return AjaxResult.success(null);
            }
            queryWrapper.in("role_name",roleName)
                    .ne("role_id",SecurityUtils.getLoginSysUser().getRoleId());
        }else{
            if (StringUtils.equals("7", authLevel)) {
                roleName.add("区域经理");
                roleName.add("业务员");
                roleName.add("员工");
                roleName.add("油企");
                roleName.add("油站");
            }
            if (StringUtils.equals("5", authLevel)) {
                roleName.add("业务员");
            }
            if (StringUtils.equals("6", authLevel)) {
            }
            if (StringUtils.equals("2", authLevel) || StringUtils.equals("3", authLevel)) {
                roleName.add("员工");
            }
            if (StringUtils.equals("1", authLevel)) {
                roleName.add("员工");
                roleName.add("油站");
            }

            if (roleName == null || roleName.size()<1){
                return AjaxResult.success(null);
            }
            queryWrapper.in("role_name", roleName)
                    .eq("create_user_id", 1);
        }


        List<SysRole> list = roleService.list(queryWrapper);
        return AjaxResult.success(list);
    }

    /**
     * 获取可分配角色
     *
     * @return
     */
    @GetMapping("/getStationStaffRoleByUser")
    public AjaxResult getStationStaffRoleByUser(String authLevel ) {
        QueryWrapper<SysRole> queryWrapper = null;
        Long userId = SecurityUtils.getLoginSysUser().getUserId();
        SysUser byId = userService.getById(userId);
        List<String> strings = new ArrayList<>();
        if(StringUtils.isNotEmpty(byId.getRoleId())){
            strings.addAll(Arrays.asList(byId.getRoleId().split(",")));
        }
        queryWrapper = new QueryWrapper<>();
        List<String> roleName = new ArrayList<>();
        roleName.add("员工");
        roleName.add("油站");
        queryWrapper.in("role_name", roleName)
                .eq("create_user_id", 1);


        List<SysRole> list = roleService.list(queryWrapper);
        return AjaxResult.success(list);
    }

    @GetMapping("/getPro")
    public AjaxResult getPro() {
        Long userId = SecurityUtils.getLoginSysUser().getUserId();
        boolean b = true;
        if (SecurityUtils.isAdmin(userId) ||SecurityUtils.isPartner()) {
            return AjaxResult.success("是", b);
        } else {
            return AjaxResult.success("否", !b);
        }
    }

    @GetMapping("/list/listEmployee")
    public TableDataInfo listEmployee(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectEmployeeList(user);
        for (int i = 0; i < list.size(); i++) {
            List<String> gun = new ArrayList<>();
            List<Long> gunnumber = new ArrayList<>();
            List<String> gunList1 = new ArrayList<>();
            if (list.get(i).getGun() != null) {
                String[] gunls = list.get(i).getGun().split(",");
                for (String ss : gunls) {
                    gun.add(ss);
                    gunnumber.add(Long.parseLong(ss));
                }
                Long[] value = new Long[gunnumber.size()];
                for (int ss = 0; ss < gunnumber.size(); ss++) {
                    value[ss] = gunnumber.get(ss);
                }
                Long temp = Long.parseLong("0");
                for (int tt = 0; tt < value.length; tt++) {
                    for (int m = tt + 1; m < value.length; m++) {
                        if (value[tt] > value[m]) {
                            temp = value[m];
                            value[m] = value[tt];
                            value[tt] = temp;
                        }
                    }
                }

                for (Long mm : value) {
                    gunList1.add(mm + "");
                }
            }
            if (list.get(i).getPushUserIds() != null) {
                list.get(i).setIdList(Arrays.asList(list.get(i).getPushUserIds().split(",")));
            } else {
                list.get(i).setIdList(new ArrayList<>());
            }
            list.get(i).setGunList(gunList1);

        }
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/exportCooperator")
    public AjaxResult exportCooperator(SysUserVo userVo) {
        SysUser user = new SysUser();
        user.setNickName(userVo.getNickName());
        user.setUserLevel("7");
        List<SysUser> list = userService.selectUserList(user);
        List<SysUserVo> voList = new ArrayList<>();
        for (SysUser sysUser : list) {
            SysUserVo sysUserVo = new SysUserVo();
            sysUserVo.setPhonenumber(sysUser.getPhonenumber());
            sysUserVo.setStatus(sysUser.getStatus());
            sysUserVo.setNickName(sysUser.getNickName());
            sysUserVo.setPartnerName(sysUser.getPartnerName());
            voList.add(sysUserVo);
        }
        ExcelUtil<SysUserVo> util = new ExcelUtil<SysUserVo>(SysUserVo.class);
        return util.exportExcel(voList, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser  aSysUser = userService.selectUserById(userId);
                    if(aSysUser.getUserLevel()!= null&&aSysUser.getUserLevel().equals("2")){
                        List<Integer>  aRole = roleService.selectRoleListByUserId(aSysUser.getUserId());
                        for(Integer roleItem : aRole){
                            SysRole bSysRole =    roleService.selectRoleById(new Long(roleItem));
                           if( bSysRole.getRoleName().equals("员工")){
                                aSysUser.setUserLevel("3");
                            }
                        }
                    }
            ajax.put(AjaxResult.DATA_TAG,aSysUser );
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/getInfoNew/{userId}"})
    public AjaxResult getInfoNew(@PathVariable(value = "userId", required = false) Long userId) {
        SysUser sysUser = userService.getById(userId);
        List<SysUserRole> sysUserRoles =
                sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getUserId()));
        List<Long> collect
                = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRole> roles = roleService.list(new QueryWrapper<SysRole>().in("role_id", collect));
        sysUser.setRoles(roles);
        if (StringUtils.isNotNull(sysUser.getRoleId())) {
            List<String> strings = Arrays.asList(sysUser.getRoleId().split(","));
            List<SysRole> list = roleService.list(new QueryWrapper<SysRole>().in("role_id", strings));
            sysUser.setRoleList(list);
        }
        if(sysUser.getUserLevel().equals("3")){
            sysUser.setUserLevel("2");
        }
        if (StringUtils.isNull(sysUser.getAuthorId())) {
            sysUser.setCreateBy("admin");
            sysUser.setAuthorId(1L);
        }
        return AjaxResult.success(sysUser);
    }


    /**
     * 根据用户信息获取当前的用户
     */
    @GetMapping(value = {"/getUserInfo/{userId}"})
    public AjaxResult getUserInfo(@PathVariable(value = "userId", required = false) Long userId) {
        SysUser sysUser = userService.selectUserById(userId);
        if (sysUser == null) {
            return AjaxResult.error("查询用户信息失败");
        }
        if (sysUser.getPushUserIds() != null) {
            sysUser.setIdList(Arrays.asList(sysUser.getPushUserIds().split(",")));
        } else {
            sysUser.setIdList(new ArrayList<>());
        }
        if (sysUser.getGun() != null) {
            sysUser.setGunList(Arrays.asList(sysUser.getGun().split(",")));
        } else {
            sysUser.setGunList(new ArrayList<>());
        }
        return AjaxResult.success(sysUser);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (user.getUserLevel() != null &&
                (user.getUserLevel().equals("5") || user.getUserLevel().equals("6")) ) {

            if( user.getRoleId() != null){


        String roleIds = user.getRoleId(); // 假设 user.getRoleId() 返回的是逗号分隔的角色 ID 字符串
            String[] roleIdArray = roleIds.split(","); // 使用逗号分割字符串，得到角色 ID 数组

            for (String roleId : roleIdArray) {
                try {
                    Long number = Long.parseLong(roleId); // 将字符串转换为 Long 类型
                    System.out.println("转换后的 Long 值为: " + number);
                    SysRole aSysRole =  roleService.selectRoleById(number);
                    if(aSysRole.getRoleName().equals("油企")){
                        return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，区域经理、业务员分配角色不能为油企");
                    }
                    if(aSysRole.getRoleName().equals("油站")){
                        return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，区域经理、业务员分配角色不能为油站");
                    }
                    if(aSysRole.getRoleName().equals("员工")){
                        return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，区域经理、业务员分配角色不能为员工");
                    }

                } catch (NumberFormatException e) {
                    System.out.println("字符串无法转换为 Long 值");
                }

            } }

            if( user.getRoleIds() != null && user.getRoleIds().length>0){



                for (Long roleId : user.getRoleIds()) {
                        SysRole aSysRole =  roleService.selectRoleById(roleId);
                        if(aSysRole.getRoleName().equals("油企")){
                            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，区域经理、业务员角色不能为油企");
                        }
                        if(aSysRole.getRoleName().equals("油站")){
                            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，区域经理、业务员角色不能为油站");
                        }
                        if(aSysRole.getRoleName().equals("员工")){
                            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，区域经理、业务员角色不能为员工");
                        }



                } }

        }
        SysUser sysUser = SecurityUtils.getLoginSysUser();
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (user.getStationId() != null) {
            redisCache.deleteObject("push:emplist:" + user.getStationId());
        }
        List<Long> longs = Arrays.asList(user.getRoleIds());
        if (StringUtils.equals("3", user.getUserLevel()) || longs.contains(25L)) {
            user.setUserLevel("2");
            boolean hasEmployeeRole = false;
            boolean hasStationRole = false;
            if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
                for (Long roleId : user.getRoleIds()) {
                    SysRole aSysRole = roleService.selectRoleById(roleId);
                    if (aSysRole.getRoleName().equals("员工")) {
                        hasEmployeeRole = true;
                    }
                    if (aSysRole.getRoleName().equals("油站")) {
                        hasStationRole = true;
                    }
                }
            }
            if (!hasEmployeeRole) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，缺少员工角色");
            }
            if (!hasStationRole) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，缺少油站角色");
            }
        }
//        if (StringUtils.isNull(user.getCreateBy()) && !StringUtils.equals("7",sysUser.getUserLevel())){
//        admin
        if(SecurityUtils.isAdmin(sysUser.getUserId())){
//            admin创建合伙人
            if(user.getUserLevel().equals("7")){
                SysUser aSysUser = userMapper.getById(sysUser.getUserId());
                user.setSupremeLevelName(aSysUser.getSupremeLevelName());
                user.setSupremeLevelId(aSysUser.getSupremeLevelId());
            }else {
                SysUser aSysUser = userMapper.getById(user.getAuthorId());
//                合伙人admin
                if(aSysUser.getUserLevel()==null || aSysUser.getUserLevel().equals("7")){
                    user.setSupremeLevelName(aSysUser.getUserName());
                    user.setSupremeLevelId(aSysUser.getUserId());
                }else{
                    user.setSupremeLevelName(aSysUser.getSupremeLevelName());
                    user.setSupremeLevelId(aSysUser.getSupremeLevelId());
                }



            }
        } else if(sysUser.getUserLevel().equals("7")){
//            合伙人
            user.setSupremeLevelName(sysUser.getUserName());
            user.setSupremeLevelId(sysUser.getUserId());
        }else {
//            非合伙人
            SysUser aSysUser  = userMapper.getById(sysUser.getUserId());
            user.setSupremeLevelName(aSysUser.getSupremeLevelName());
            user.setSupremeLevelId(aSysUser.getSupremeLevelId());
        }
        user.setPartnerName(user.getNickName());
        user.setAuthorId(sysUser.getUserId());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增合伙人
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "新增合伙人", businessType = BusinessType.INSERT)
    @PostMapping("/addPartner")
    public AjaxResult addPartner(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getPhonenumber()))) {
            return AjaxResult.error("新增用户'" + user.getNickName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getNickName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getNickName() + "'失败，合伙人名称已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setUserLevel("7");
        user.setAuthLevel("1");
        user.setDeptId(100L);
        user.setCreateBy(SecurityUtils.getUsername());
        user.setSupremeLevelId(1L);
        user.setSupremeLevelName("admin");
        user.setAuthorId(SecurityUtils.getLoginSysUser().getUserId());
        List<SysRole> sysRoles =
                roleService.list(new QueryWrapper<SysRole>().eq("role_name", "合伙人"));
        String roleIds = sysRoles.stream().map(role -> String.valueOf(role.getRoleId())).collect(Collectors.joining(","));

        user.setRoleIds(sysRoles.stream().map(SysRole::getRoleId).toArray(Long[]::new));
        user.setRoleId(roleIds);
        if (user.getStationId() != null) {
            redisCache.deleteObject("push:emplist:" + user.getStationId());
        }
        return toAjax(userService.insertUser(user));
    }


    /**
     * 修改合伙人
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "修改合伙人", businessType = BusinessType.INSERT)
    @PutMapping("/editPartner")
    public AjaxResult editPartner(@RequestBody SysUser user) {
        /*if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getPhonenumber()))) {
            return AjaxResult.error("修改用户'" + user.getNickName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getNickName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getNickName() + "'失败，合伙人名称已存在");
        }*/
        SysUser sysUser = userService.selectUserByUserName(user.getPhonenumber());
        if(!StringUtils.equals(user.getPhonenumber(),sysUser.getPhonenumber())){
            return AjaxResult.error("修改手机号请联系管理员");
        }
        user.setUserId(sysUser.getUserId());
        return toAjax(userMapper.updateUser(user));
    }


    @ApiOperation("修改员工信息")
    @ApiImplicitParam(name = "sysUser", value = "新增用户信息", dataType = "SysUser")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/editUser")
    public AjaxResult editUser(@RequestBody SysUser user) {
        String gun = "";
        String userids = "";
        userService.checkUserAllowed(user);
//        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        }
//        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        if (user.getGunList() != null && user.getGunList().size() > 0) {
            for (String ss : user.getGunList()) {
                if ("".equals(gun)) {
                    gun += ss;
                } else {
                    gun += "," + ss;
                }
            }
            user.setGun(gun);
        }
        if (user.getIdList() != null && user.getIdList().size() > 0) {
            for (String ss : user.getIdList()) {
                if ("".equals(userids)) {
                    userids += ss;
                } else {
                    userids += "," + ss;
                }
            }
            user.setPushUserIds(userids);
        }
        Long[] roles = {(long) 19};
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setRoleIds(roles);
        if (user.getStationId() != null) {
            redisCache.deleteObject("push:emplist:" + user.getStationId());
            redisCache.deleteObject("userid:" + user.getUserId());
            redisCache.deleteObject("price:" + user.getStationId() + ":" + user.getUserId());
        }
        if (StringUtils.equals("3", user.getUserLevel())) {
            user.setEmployeeOrNot("1");
            user.setUserLevel("2");
        } else {
            user.setEmployeeOrNot("0");
            user.setUserLevel("2");
        }
        return toAjax(userService.updateUser(user));
    }




    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        String gun = "";
        userService.checkUserAllowed(user);
//        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        }
//        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        if (user.getGunList() != null && user.getGunList().size() > 0) {
            for (String ss : user.getGunList()) {
                if ("".equals(gun)) {
                    gun += ss;
                } else {
                    gun += "," + ss;
                }
            }
            user.setGun(gun);
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        if (user.getStationId() != null) {
            redisCache.deleteObject("push:emplist:" + user.getStationId());
            redisCache.deleteObject("userid:" + user.getUserId());
            redisCache.deleteObject("price:" + user.getStationId() + ":" + user.getUserId());
        }
        if (StringUtils.equals("3", user.getUserLevel())) {
            user.setUserLevel("2");
            boolean hasEmployeeRole = false;
            boolean hasStationRole = false;

            if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
                for (Long roleId : user.getRoleIds()) {
                    SysRole aSysRole = roleService.selectRoleById(roleId);
                    if (aSysRole.getRoleName().equals("员工")) {
                        hasEmployeeRole = true;
                    }
                    if (aSysRole.getRoleName().equals("油站")) {
                        hasStationRole = true;
                    }
                }
            }

            if (!hasEmployeeRole) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，缺少员工角色");
            }

            if (!hasStationRole) {
                return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，缺少油站角色");
            }
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        int i = userService.deleteUserByIds(userIds);
        if (userIds != null && userIds.length > 0) {
            for (Long id : userIds) {
                SysAgent sysAgent = new SysAgent();
                sysAgent.setUserId(id);
                sysAgentService.deleteSysAgent(sysAgent);
            }
        }
        return toAjax(i);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 代理开启修改
     */
    @Log(title = "修改用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeAgentFlag")
    @Transactional
    public AjaxResult changeAgentFlag(@RequestBody SysUser user) {
        int i = 0;
        try {
            user.setUpdateBy(SecurityUtils.getUsername());
            if (user.getAgentFlag() != null && user.getAgentFlag().equals("0") && user.getUserId() != null) {
                i = userService.updateUserAgentFlag(user);
                SysAgent sysAgent = new SysAgent();
                sysAgent.setUserId(user.getUserId());
                sysAgentService.deleteSysAgent(sysAgent);
            } else if (user.getAgentFlag() != null && user.getAgentFlag().equals("1")) {
                i = userService.updateUserAgentFlag(user);
            }
        } catch (Exception e) {
            System.out.println("代理开启权限" + e.getLocalizedMessage() + "");
            e.printStackTrace();
        }

        return toAjax(i);
    }

    /**
     * 用户修改密码校验
     *
     * @param loginBody
     * @return
     */
    @ApiOperation("用户密码校验(客户端)")
    @PostMapping("/checkUserPwd")
    public AjaxResult checkUserPwd(@RequestBody LoginBody loginBody) {
        if (StringUtils.isEmpty(loginBody.getPassword())) {
            return AjaxResult.error("密码不能为空");
        }
        return AjaxResult.success(bCryptPasswordEncoder.matches(loginBody.getPassword(), SecurityUtils.getLoginUser().getPassword()));
    }

    /**
     * 用户修改密码 修改之后 需要登出所有已登录账户
     *
     * @return
     */
    @ApiOperation("修改密码(客户端)")
    @PostMapping("/updateUserPwd")
    public AjaxResult updateUserPwd(@RequestBody SysUser user, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(user.getPassword(), user.getNewPassword(), user.getConfirmPassword())) {
            return AjaxResult.error("参数异常");
        }
        // 先校验旧密码是否正确
        if (!bCryptPasswordEncoder.matches(user.getPassword(), SecurityUtils.getLoginUser().getPassword())) {
            return AjaxResult.error("旧密码输入错误");
        }
        // 对比确认密码
        if (!user.getNewPassword().equals(user.getConfirmPassword())) {
            return AjaxResult.error("新密码输入不一致");
        }
        // 修改并登出用户
        user.setUserId(SecurityUtils.getLoginSysUser().getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getNewPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        userService.resetPwd(user);
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUserByApplet(loginUser.getToken(), SecurityUtils.getUsername());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        return AjaxResult.success("修改成功");
    }

}
